package com.zhanhong.opencvdemo.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.TypedValue;

import com.zhanhong.opencvdemo.core.Core;

import java.io.File;
import java.io.FileOutputStream;

public class BitmapUtils {

    private BitmapUtils() {
    }

    public static Bitmap changeBitmapSize(Bitmap srcBitmap, int targetWidth, int targetHeight) {
        int srcWidth = srcBitmap.getWidth();
        int srcHeight = srcBitmap.getHeight();
        float scaleWidth = ((float) targetWidth) / srcWidth;
        float scaleHeight = ((float) targetHeight) / srcHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(srcBitmap, 0, 0, srcWidth, srcHeight, matrix, true);
    }

    public static Bitmap rotateImageView(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Bitmap loadBitmap(String bitmapPath) {
        return BitmapFactory.decodeFile(bitmapPath);
    }

    public static Bitmap loadBitmap(int resId, int newWidth, int newHeight) {
        Resources resources = Core.getApplicationContext().getResources();
        BitmapFactory.Options options = new BitmapFactory.Options();
        TypedValue value = new TypedValue();
        resources.openRawResource(resId, value);
        options.inTargetDensity = value.density;
        options.inScaled = false;
        Bitmap originBitmap = BitmapFactory.decodeResource(resources, resId, options);
        if (newWidth > 0 && newHeight > 0) {
            return changeBitmapSize(originBitmap, newWidth, newHeight);
        } else {
            return originBitmap;
        }
    }

    public static Bitmap loadBitmap(int resId) {
        return loadBitmap( resId, 0, 0);
    }

    public static void save(Bitmap bm, File file) {
        save(bm, file, 100);
    }

    public static void save(Bitmap bm, File file, int quality) {
        try {
            if (bm != null && file != null) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                bm.compress(CompressFormat.PNG, quality, new FileOutputStream(file));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
